<?php

namespace app\common\model\mysql\system;

use app\common\exception\MessageException;
use app\common\model\mysql\BaseModel;
use think\model\concern\SoftDelete;


class Department extends BaseModel
{
    use SoftDelete;

    protected $deleteTime = 'delete_time';

    // 设置当前模型对应的完整数据表名称
    protected $table = 'sys_department';

    // 定义主键 alter table users AUTO_INCREMENT=10000;

    protected $pk = 'id';

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 默认根节点
    public static $rootParent = 0;

    // 模型初始化
    protected static function init()
    {
        // TODO:初始化内容
    }

    // 检查分类名是否存在
    public static function checkName($name, $id = null)
    {
        if (!$name) {
            throw new MessageException(['msg' => '部门名称不合法']);
        }

        if (isset($id)) {
            return self::where('name', $name)->where('id', '<>', $id)->find();
        }

        return self::where('name', $name)->find();
    }

    // 部门列表
    public static function listTree($params)
    {
        $where = [];
        $order = [
            'sort' => 'desc',
            'update_time' => 'desc',
            'create_time' => 'desc',
            'id' => 'desc'
        ];

        if (!empty($params['name'])) {
            $where[] = ['name', 'like', '%' . $params['name'] . '%'];
        }
        if (isset($params['status']) && $params['status'] != '') {
            $where[] = ['status', '=', $params['status']];
        }
        $lists = self::where($where)
            ->append(['status_desc'])
            ->order($order)
            ->select()
            ->toArray();

        $pid = 0;
        if (!empty($lists)) {
            $pid = min(array_column($lists, 'parent_id'));
        }
        return self::getTree($lists, $pid);
    }

    /**
     * 获取树状列表
     * @param $array
     * @param int $pid
     * @param int $level
     * @return array
     */
    public static function getTree($array, $pid = 0, $level = 0)
    {
        $list = [];
        foreach ($array as $key => $item) {
            if ($item['parent_id'] == $pid) {
                $item['level'] = $level;
                // 没有子元素，不返回 children
                $children = self::getTree($array, $item['id'], $level + 1);
                !empty($children) && $item['children'] = $children;
                $list[] = $item;
                // 减少下次循环数
                unset($array[$key]);
            }
        }
        return $list;
    }

    // 添加
    public static function add(array $params)
    {
        self::create([
            'parent_id' => $params['parent_id'] ?? self::$rootParent,
            'name' => $params['name'],
            'leader' => $params['leader'] ?? '',
            'mobile' => $params['mobile'] ?? '',
            'email' => $params['email'] ?? '',
            'remark' => $params['remark'] ?? '',
            'status' => $params['status'],
            'sort' => $params['sort'] ?? 0
        ]);
    }

    // 更新
    public static function edit(array $params)
    {
        try {
            $pid = $params['parent_id'];
            $oldDeptData = self::findOrEmpty($params['parent_id']);
            if ($oldDeptData['parent_id'] == self::$rootParent) {
                $pid = self::$rootParent;
            }
            self::update([
                'id' => $params['id'],
                'parent_id' => $pid,
                'name' => $params['name'],
                'leader' => $params['leader'] ?? '',
                'mobile' => $params['mobile'] ?? '',
                'email' => $params['email'] ?? '',
                'remark' => $params['remark'] ?? '',
                'status' => $params['status'],
                'sort' => $params['sort'] ?? 0
            ]);
        } catch (\Exception $e) {
            throw new MessageException(['msg' => $e->getMessage()]);
        }
    }

    public static function remove(array $params)
    {
        try {
            // TODO 有子部门，关联了用户都不允许删除
            self::destroy($params['id']);
        } catch (\Exception $e) {
            throw new MessageException(['msg' => $e->getMessage()]);
        }
    }
}